package com.avyss.flyingpoints.scene;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.graphics.Paint;

public class Scene {

	private final DynamicsParams 		params;
	
	private final Leader 				leader;
	private final ArrayList<Follower>	followers;
	
	//color for the followers (degrees inside the color circle)
	private int 	nCurrentColorPhase;		
	private Paint 	rotatingColorPaint;
	private Paint 	whitePaint;
	
	public Scene(int windowWidth, int windowHeight) {
		params = new DynamicsParams(windowWidth, windowHeight);
		
		leader    = new Leader(params);
		followers = new ArrayList<Follower>();
	    for (int i = 0; i < params.getNumOfFollowers(); i++) {
	    	followers.add(new Follower(params));
	    }

	    whitePaint = new Paint();
		whitePaint.setStyle(Paint.Style.STROKE);
		whitePaint.setStrokeWidth(3);
		whitePaint.setARGB(255, 255, 255, 255);
		
	    rotatingColorPaint = new Paint();
		rotatingColorPaint.setStyle(Paint.Style.STROKE);
		rotatingColorPaint.setStrokeWidth(2);
	    
	    // set initial color for the followers
	    nCurrentColorPhase = 0;
	    putColorToRotaitingPaint(nCurrentColorPhase);
	}
	
	public void placeLeader(float x, float y) {
		leader.forcePlacement(x, y);
		leader.forceRandomDir();
	}
	
	public void calcNextState(long timeStepMs) {

	    // Move the points
	    for (Follower follower: followers) {
	    	follower.applyMove(timeStepMs);
	    	follower.adjustVelociyFollower(leader, timeStepMs);
	    }

	    // Move the leader
	    leader.applyMove(timeStepMs); 

	    // Change direction of leader
	    leader.adjustVelociyLeader(timeStepMs);
	    
	    // Change color of flying points
	    nCurrentColorPhase += (timeStepMs * params.getColorPhaseRate()) % 360;
	    putColorToRotaitingPaint(nCurrentColorPhase);
	}

	private void putColorToRotaitingPaint(int nCurrentColorPhase) {
	    int colorR = (int) (127 * (1 + Math.sin((nCurrentColorPhase +   0) / 180.0 * Math.PI)));
	    int colorG = (int) (127 * (1 + Math.sin((nCurrentColorPhase + 120) / 180.0 * Math.PI)));
	    int colorB = (int) (127 * (1 + Math.sin((nCurrentColorPhase + 240) / 180.0 * Math.PI)));
		rotatingColorPaint.setARGB(255, colorR, colorG, colorB);
	}
	
	public void drawCurrentState(Canvas canvas) {
	    // clear the back picture
		canvas.drawARGB(255, 0, 0, 0);
		
		// draw the leader
		leader.draw(canvas, whitePaint);

	    // draw the rest
	    for (Follower follower: followers) {
	    	follower.draw(canvas, rotatingColorPaint);
	    }
		
	}

}
